<?php

namespace App\Http\Controllers\Api\Common;

use App\Http\Controllers\Controller;
use App\Models\Train\TrainOrders\Repositories\Interfaces\TrainOrdersRepositoryInterface;
use App\Notifications\Train\TrainOrder\TicketSuccessNotify;
use App\Trip\Wechat\Account\WechatOfficialLogin;
use Closure;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

class WeiXinController extends Controller
{

    private Application $official_app;

    public function __construct()
    {

    }

    /**
     */
    public function callback(string $business, Request $request)
    {
        if ($business == 'official') {
            $w                  = new WechatOfficialLogin();
            $this->official_app = $w->application();
            $server             = $this->official_app->getServer();
            Log::info("access_token:".$w->access_token());
            // g改签失败
            $api = $this->official_app->getClient();
            //
            $server->with(function ($message, Closure $next) use ($server, $api, $w) {
                if ($message->MsgType == "event") {
                    // 取消关注
                    if ($message->Event == "unsubscribe") {
                        $w->unsubscribe($message->FromUserName);
                    }
                    if ($message->Event == "subscribe") {
                        $w->subscribe($message->FromUserName);
                    }
                }

                if ($message->MsgType == 'text') {
                    if ($message->Content == '绑定' || strlen($message->FromUserName) == 28 && !$w->getOfficialUser($message->FromUserName)) {
                        // 发送客服消息
                        $url = URL::to('/h5/weixin.html');
                        $api->postJson('/cgi-bin/message/custom/send', [
                            'touser'  => $message->FromUserName,
                            'msgtype' => 'text',
                            'text'    => [
                                'content' => "<a href='{$url}'>点我获取更多福利</a>",
                            ],
                        ]);
                    }

                    if (Str::length($message->Content) == 17) {
                        $orderRepo = app(TrainOrdersRepositoryInterface::class);
                        $order     = $orderRepo->getOrderInfo($message->Content);
                        $order?->notify((new TicketSuccessNotify($order)));
                    }


                }
                return [
                    'MsgType' => 'text',
                    'Content' => "这是被动回复的消息,欢迎使用公众号业务",
                ];
            });

            return $server->serve();
        }
    }
}
